<template>
  <div class="json-formatter">
    <h2>JSON 格式化</h2>
    <textarea v-model="jsonInput" placeholder="输入 JSON 字符串" rows="7"></textarea>
    <button @click="formatJSON">格式化</button>
    <textarea v-model="formattedJSON" placeholder="格式化结果" rows="7" readonly></textarea>
    <p v-if="errorMessage" class="error">{{ errorMessage }}</p>
  </div>
</template>

<script>
export default {
  name: 'JSONFormatter',
  data() {
    return {
      jsonInput: '',
      formattedJSON: '',
      errorMessage: '',
    };
  },
  methods: {
    formatJSON() {
      try {
        const parsed = JSON.parse(this.jsonInput);
        this.formattedJSON = JSON.stringify(parsed, null, 2);
        this.errorMessage = '';
      } catch (err) {
        this.errorMessage = '无效的 JSON 字符串';
        this.formattedJSON = '';
      }
    },
  },
};
</script>

<style scoped>
.json-formatter {
  max-width: 600px;
  margin: 0 auto;
  text-align: center;
}
textarea {
  width: 100%;
  margin: 10px 0;
  padding: 10px;
  font-size: 16px;
  font-family: 'Courier New', monospace;
  border: 1px solid #ccc;
  border-radius: 4px;
  transition: border-color 0.3s;
}
textarea:focus {
  border-color: #3498db;
}
button {
  padding: 10px 20px;
  margin-bottom: 10px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}
button:hover {
  background-color: #2980b9;
}
.error {
  color: red;
  margin-top: 10px;
}
</style> 